from xml.dom.minidom import parse

def get_title(f):
    document = parse(f)
    if document.getElementsByTagName('rss'): # RSS feed
        for elem in document.getElementsByTagName('title'):
            if elem.parentNode.nodeName == 'channel':
                title = elem.firstChild.nodeValue
                break
    elif document.getElementsByTagName('feed'): # Atom feed
        for elem in document.getElementsByTagName('title'):
            if elem.parentNode.nodeName == 'feed':
                title = elem.firstChild.nodeValue
                break
    return title


def get_item_list(f):
    def rss_element2dict(item):
        d =  {tag: item.getElementsByTagName(tag)[0].firstChild.nodeValue
                for tag in ('title', 'link', 'description')}
        try: # guid is not required
            d['guid'] = item.getElementsByTagName('guid')[0]\
                            .firstChild.nodeValue
        except:
            d['guid'] = d['link']
        return d

    def atom_element2dict(entry):
        d = {}
        d['title'] = entry.getElementsByTagName('title')[0]\
                        .firstChild.nodeValue
        d['guid'] = entry.getElementsByTagName('id')[0]\
                        .firstChild.nodeValue
        for link in entry.getElementsByTagName('link'):
            if link.getAttribute('rel') in ('', 'alternate'):
                d['link'] = link.getAttribute('href')
                break
        d['description'] = entry.getElementsByTagName('content')[0]\
                            .firstChild.nodeValue
        return d

    document = parse(f)
    if document.getElementsByTagName('rss'): # RSS feed
        itemlist = map(rss_element2dict,
                       document.getElementsByTagName('item'))
    elif document.getElementsByTagName('feed'): # Atom feed
        itemlist = map(atom_element2dict,
                       document.getElementsByTagName('entry'))
    return itemlist
